import { addUserApplet, delUserApplet, getUserAppletList, modUserApplet } from "@/api/modules/applet/userApplet";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import AppletSource from "@/components/Sansan/Status/AppletSource";
import ServerType from "@/components/Sansan/Status/ServerType";
import BaseSearchForm from "@/components/SearchForm/BaseSearchForm";
import SearchTypes from "@/components/SearchForm/SearchTypes";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { useApplet } from "@/hooks/useApplet";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { Dict } from "@/stores/interface";
import { DictType, getDictList } from "@/utils/cacheUtil";
import { gotoPage } from "@/utils/routerUtil";
import { confirm, showMsg, showTips } from "@/utils/util";
import BasicDialog from "../components/detailDialog";
import { useRouter, useRoute } from "vue-router";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
export default defineComponent({
	name: "AppletDevelopList",
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const { gotoAccess } = useApplet();
		const router = useRouter();
		const route = useRoute();
		const initParam = reactive({ appType: "", name: "" });
		const collapsedSearch = ref(false);
		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};
		onActivated(() => {
			proTable.value.getTableList();
		});
		const typeList = ref<any>([] as Dict[]);
		const btnList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			useAuthButtons().then(res => {
				btnList.value = res.filter((item: any) => !item.btnGroup);
			});
			getDictList(DictType.AppletType).then(list => {
				typeList.value = list;
			});
		});
		const detailDialog = reactive<any>({
			title: proxy?.$t("develop.dialog_title.detail"),
			visible: false,
			detail: {}
		});
		const clickBtn = async (fn: string, row: any) => {
			console.log(fn);
			let selected = row.selectList ? row.selectList : [row];
			switch (fn) {
				case "detail":
				case "mod":
					if (selected.length != 1) {
						showMsg(proxy?.$t("develop.msg.modify"), MessageType.warning);
						return;
					}
					detailDialog.title = proxy?.$t("develop.dialog_title.modify");
					detailDialog.detail = { ...selected[0] };
					detailDialog.visible = true;
					break;
				case "add":
					detailDialog.title = proxy?.$t("develop.dialog_title.add");
					detailDialog.detail = {};
					detailDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("develop.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("develop.confirm.del") }).then(flag => {
						flag && submitDel({ id: selected.map((item: any) => item.id).join(",") });
					});
					break;
				case "gotoDevice":
					gotoPage(RouterPath.deviceDetail, { sn: selected[0].sn });
					break;
				case "gotoApplet":
					gotoAccess({ ...selected[0] });
					break;
				case "gotoAppletDetail":
					router.push({
						path: RouterPath.appletDetail,
						query: { id: selected[0].id, key: selected[0].key, menuId: route.meta.id as string }
					});
					break;
			}
		};
		// 表格配置项
		const columns: ColumnProps[] = [
			//应用		应用类型	来源		开发者	最后更新时间	版本 ？？	操作
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "name", label: proxy?.$t("develop.tablist_label.name"), search: { el: "input" } },
			{ prop: "key", label: proxy?.$t("develop.tablist_label.key"), width: 100 },
			{ prop: "appType", label: proxy?.$t("develop.tablist_label.type"), width: 100, search: { slot: {} } },
			{ prop: "source", label: proxy?.$t("develop.tablist_label.source"), width: 100 },
			{ prop: "creator", label: proxy?.$t("develop.tablist_label.creator"), width: 80 },
			{ prop: "owner", label: proxy?.$t("develop.tablist_label.owner"), width: 80 },
			{ prop: "updateTime", label: proxy?.$t("develop.tablist_label.update_time") },
			{ prop: "version", label: proxy?.$t("develop.tablist_label.version"), width: 100 },
			{ prop: "desc", label: proxy?.$t("develop.tablist_label.desc"), width: 100 },
			{ prop: "operation", label: proxy?.$t("develop.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const submitDel = async (dataInfo: any) => {
			let res = await delUserApplet({ ...dataInfo });
			let ok = showTips(res.code, proxy?.$t("develop.tips.del"), res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submitDetail = async () => {
			let api = detailDialog.detail.id ? modUserApplet : addUserApplet;
			let res = await api(detailDialog.detail);
			let ok = showTips(
				res.code,
				detailDialog.detail.id ? proxy?.$t("develop.tips.mod") : proxy?.$t("develop.tips.add"),
				res.message
			);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.reset();
			}
		};
		const more = ref(false);
		return () => {
			return (
				<div>
					<BasicDialog
						width="800px"
						title={detailDialog.title}
						v-model:visible={detailDialog.visible}
						detail={detailDialog.detail}
						onSubmit={submitDetail}
					></BasicDialog>
					{collapsedSearch.value ? null : (
						<BaseSearchForm class="mb-2">
							<el-form
								class="flex pt-4 pl-4 pr-4 bg-white"
								style="flex-wrap: wrap;"
								onKeyup={(e: KeyboardEvent) => (e.keyCode == 13 ? proTable.value.getTableList() : null)}
							>
								<el-form-item class="search-item" label={proxy?.$t("develop.form_label.app_type")}>
									<SearchTypes v-model={initParam.appType} dataList={typeList.value} />
								</el-form-item>
								<el-form-item class="search-item">
									<el-link
										type="primary"
										underline={false}
										onClick={() => {
											more.value = !more.value;
										}}
									>
										{proxy?.$t("tabs.more")}
									</el-link>
								</el-form-item>
								{more.value ? (
									<el-form-item class="search-item">
										<el-input v-model={initParam.name} placeholder={proxy?.$t("develop.placeholder.name")}></el-input>
									</el-form-item>
								) : null}
							</el-form>
						</BaseSearchForm>
					)}
					<ProTable
						ref={proTable}
						custSearch
						onSearchCollapsed={val => {
							collapsedSearch.value = val;
						}}
						title={btnList.value.length ? "" : proxy?.$t("develop.tab_title.manage")}
						columns={columns}
						requestApi={getUserAppletList}
						initParam={initParam}
						dataCallback={dataCallback}
						ignoreInit
					>
						{{
							tableHeader: (scope: any) => {
								return btnList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							name: (scope: any) => {
								return (
									<div class="truncate cursor-pointer primary-color" onClick={() => clickBtn("gotoAppletDetail", scope.row)}>
										{scope.row.name}
									</div>
								);
							},
							source: (scope: any) => {
								return <AppletSource v-model={scope.row.source} />;
							},
							appType: (scope: any) => {
								return <ServerType v-model={scope.row.appType} />;
							},
							operation: (scope: any) => {
								return (
									<>
										<el-link
											type="danger"
											link
											class="iconfont icontrash-2"
											onClick={() => {
												clickBtn("del", scope.row);
											}}
										>
											{proxy?.$t("develop.link.del")}
										</el-link>
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("gotoAppletDetail", scope.row);
											}}
										>
											{proxy?.$t("develop.link.config")}
										</el-link>
									</>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
